import pkg from 'pg';
import mysql from 'mysql2/promise';

const { Pool } = pkg;

// 配置数据库类型，可选值为 'postgres' 或 'mysql'
const DB_TYPE = process.env.DB_TYPE || 'postgres';

// 配置数据库连接信息
const dbConfig = {
  postgres: {
    user: process.env.PG_USER || 'postgres',
    host: process.env.PG_HOST || '127.0.0.1',
    database: process.env.PG_DATABASE || 'postgres',
    password: process.env.PG_PASSWORD || 'postgres',
    port: process.env.PG_PORT || 5432,
  },
  mysql: {
    host: process.env.MYSQL_HOST || '39.106.231.209',
    user: process.env.MYSQL_USER || 'admin',
    password: process.env.MYSQL_PASSWORD || 'admin@123Lei',
    database: process.env.MYSQL_DATABASE || 'test',
    port: process.env.MYSQL_PORT || 3306,
  },
};

// 根据数据库类型创建连接池
let pool;
if (DB_TYPE === 'postgres') {
  pool = new Pool(dbConfig.postgres);
} else if (DB_TYPE === 'mysql') {
  pool = mysql.createPool(dbConfig.mysql);
} else {
  throw new Error('Unsupported database type');
}

// 测试数据库连接
const testConnection = async () => {
  try {
    let client;
    if (DB_TYPE === 'postgres') {
      client = await pool.connect();
      await client.query('SELECT NOW()');
      client.release();
    } else if (DB_TYPE === 'mysql') {
      client = await pool.getConnection();
      await client.query('SELECT NOW()');
      client.release();
    }
    console.log(`${DB_TYPE} Database connection successful`);
  } catch (error) {
    console.error(`Error connecting to the ${DB_TYPE} database:`, error);
  }
};

// 封装通用的查询方法
const query = async (sql, values) => {
  if (DB_TYPE === 'postgres') {
    return pool.query(sql, values);
  } else if (DB_TYPE === 'mysql') {
    return pool.execute(sql, values);
  }
};

// 导出连接池、测试连接方法和查询方法
export { pool, testConnection, query };